/**
 * Created by IntelliJ IDEA
 * author: Administrator
 * date: 2019/3/21 12:03
 * description:连接数据库、对数据库操作及关闭数据库
 */
package cn.mengzhiyi.guimei.dao;

import java.sql.*;

public class BaseDao {
    public Connection coon=null;
    public Statement st=null;
    public PreparedStatement ps=null;
    public ResultSet rs=null;

    /**
     * 创建连接
     * */
    public  boolean openConnection(){
        boolean flag=false;
        //连接数据库
        try {
            //加载驱动
            Class.forName("com.mysql.jdbc.Driver");
            //建立连接
            coon = DriverManager.getConnection("jdbc:mysql://localhost:3306/guimeimall", "root","123456");
            flag=true;
        }
        catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return flag;
    }
    /**
     * 查询数据
     */

    public ResultSet executeSelect(String sql,Object[] params){
        if (openConnection()){
            try {
                ps=coon.prepareStatement(sql);
                for (int i = 0; i <params.length ; i++) {
                    ps.setObject(i+1,params[i]);
                }
                rs=ps.executeQuery();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        return rs;
    }
    /**
     * 更新数据
     */
    public int executeUpdateRows(String sql,Object[] params){
        int ir=0;
        if (openConnection()){
            try {
                ps=coon.prepareStatement(sql);
                for (int i = 0; i <params.length ; i++) {
                    ps.setObject(i+1,params[i]);
                }
                ir=ps.executeUpdate();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        return ir;
    }
    /**
     * 关闭连接
     */

    public  void closeConnection(){
        try {
            if (rs!=null){
                rs.close(); }
            if (st!=null){
                st.close(); }
            if (ps!=null){
                ps.close(); }
            if (coon!=null){
                coon.close(); }
            System.out.println("数据库已成功关闭！");
        }
        catch (SQLException e) {
            e.printStackTrace();
        }
    }
}
